package dao;

import java.sql.*;

import static org.springframework.jdbc.support.JdbcUtils.closeConnection;

public class BaseDao {
    // 数据库驱动
    private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    // 数据库连接 URL
    private static final String JDBC_URL = "jdbc:mysql://localhost:3307/conveniencestore?serverTimezone=GMT-8";
    // 数据库用户名
    private static final String JDBC_USERNAME = "root";
    // 数据库密码
    private static final String JDBC_PASSWORD = "123456";

    // 加载数据库驱动
    static {
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 获取数据库连接
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void closeAll(Connection conn, Statement stat, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public int update(String sql, Object[] arr) {
        Connection connection = getConnection();
        PreparedStatement ps = null;
        int num = 0;
        try {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {
                ps.setObject(i + 1, arr[i]);
            }
            num = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(connection, ps, null);
        }
        return num;
    }

    // 测试数据库连接
    public static void main(String[] args) {
        Connection connection = getConnection();
        if (connection != null) {
            System.out.println("数据库连接成功！");
            closeConnection(connection);
        } else {
            System.out.println("数据库连接失败！");
        }
    }
}
